package xyz.penghaonan.wificonnect.sockethelper;

import android.text.TextUtils;

import com.penghaonan.appframework.AppDelegate;
import com.penghaonan.appframework.utils.Logger;
import com.penghaonan.appframework.utils.WeakObservableList;
import com.penghaonan.appframework.utils.threadpool.ThreadPoolTask;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketHelper extends BaseSocketHelper {

    private ServerSocket serverSocket = null;
    private Socket socket = null;

    private boolean isQuitReadMessage;
    private boolean isQuitReadClient;

    @Override
    public void release() {
        super.release();
        isQuitReadMessage = true;
        isQuitReadClient = true;
        IOHelper.closeOutputStream(outputStream);
        IOHelper.closeInputStream(inputStream);
        IOHelper.closeSocket(socket);
        IOHelper.closeServerSocket(serverSocket);
    }

    public ServerSocketHelper() {
        super();
        new Thread() {
            @Override
            public void run() {
                super.run();
                initSocket();
            }
        }.start();
        new Thread() {
            @Override
            public void run() {
                super.run();
                receive();
            }
        }.start();
    }

    private void initSocket() {
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            Logger.i("socket instance created");
            // 需要设置为无限超时
//            serverSocket.setSoTimeout(10000);
            while (!isQuitReadClient) {
                Logger.i("socket before connect");
                socket = serverSocket.accept();
                Logger.i("after before connect");
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
                Logger.i("socket connected");
                connectObserver.iterate(new WeakObservableList.OnIterator<DeviceConnectListener>() {
                    @Override
                    protected boolean onIterator(DeviceConnectListener item) {
                        item.onDeviceConnectStateChanged(DeviceConnectListener.STATE_CONNECTED);
                        return false;
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void receive() {
        try {
            while (!isQuitReadMessage) {
                Thread.sleep(500);
                String text = IOHelper.readText(inputStream);
                if (TextUtils.isEmpty(text)) {
                    continue;
                }
                String[] dataArray = text.split("\n");
                for (String data : dataArray) {
                    postToUI(data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean send(final String text) {
        if (outputStream == null) {
            return false;
        }
        AppDelegate.postAsync(new ThreadPoolTask() {
            @Override
            protected void doInBackground() {
                if (isReleased()) {
                    return;
                }
                if (!socket.isConnected()) {
                    release();
                    return;
                }

                try {
                    IOHelper.writeText(outputStream, text);
                } catch (IOException e) {
                    e.printStackTrace();
                    release();
                }
            }
        });
        return true;
    }
}
